$(document).ready(function() {
	var cache = {};
	$('#province > li > a').on('click', function(e) {
        e.preventDefault();
		var pronvince = $(this).attr('id');
		$('#btnLocation > .location').html($(this).attr('data-name'));
		$('#pronvinceId').val(pronvince);
        $('#branch .title > span').html($(this).attr('data-name'));

        if(typeof cache[pronvince] != "undefined") {
            renderBranches(cache[pronvince]);
        } else {
			$.ajax({
				url: '/branches/' + pronvince,
				dataType: 'json'
            }).done(function(data) {

				if (data.branches.length > 0) {
                    cache[pronvince] = data;
                    renderBranches(data);
                } else {
                    cache[pronvince] = '';
                }
            });
        }

    });

    var renderBranches = function (data) {
        renderATM(data.province, data.atms);
        var branches = data.branches;
        var branchTemplate = $("#dataBranch").html();
        $("#listBranch").html(_.template(branchTemplate,{items:branches}));
    };

    var renderATM = function(province, atms) {
        var isZoom = false;
        var atmTemplate = $("#atmInfo").html();

        map.removeMarkers();
        if ( atms.length > 0 ) {
            
            $(atms).each(function(index, atm){
                isZoom = true;
                map.addMarker({
                            lat: atm.lat,
                            lng: atm.lng,
                            title: atm.name,
                            infoWindow: {
                                content: _.template(atmTemplate, {atm:atm})
                            }
                        });
            });
        }
        if (isZoom) {
            map.fitZoom();
        } else {
            map.addMarker({
                lat: province.lat,
                lng: province.lng,
                title: province.name,
                infoWindow: {
                    content: '<h3>'+ province.name +'</h3>'
                }
            });
            map.setZoom(12);
            map.setCenter(province.lat, province.lng);
            
        }
        //map.setCenter(province.lat, province.lng);
        
    };
    // Click on the branch
    //$("#listBranch").on('click', function(){
     //   console.log($(this).attr('id'));
    //});
});